package org.mm.proxycache.http.codec;

import org.apache.mina.common.IoBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.mm.proxycache.http.HttpChunk;
import org.mm.proxycache.http.HttpRequest;

public class HttpRequestEncoder extends HttpEncoder
{

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.mina.filter.codec.ProtocolEncoder#encode(org.apache.mina.common.IoSession,
     *      java.lang.Object,
     *      org.apache.mina.filter.codec.ProtocolEncoderOutput)
     */
    public void encode( IoSession session, Object message, ProtocolEncoderOutput out )
            throws Exception
    {
        if ( message instanceof HttpChunk )
        {
            HttpChunk chunk = (HttpChunk) message;
            encodeChunk( chunk, out );
            return;
        }

        HttpRequest req = (HttpRequest) message;

        IoBuffer buf = IoBuffer.allocate( 512, false );
        buf.setAutoExpand( true );

        buf.putString( req.method().toString(), charsetEncoder );
        buf.put( (byte) ' ' );
        buf.putString( req.url().toString(), charsetEncoder );
        buf.put( (byte) ' ' );
        buf.putString( req.version().toString(), charsetEncoder );

        encode( req, buf );
        buf.flip();
        out.write( buf );
        
        // if ( req.getContentLength() == 0
     //         && !"chunked".equals( req.getHeader( "Trasnfer-Encoding" ) ) )
     //     out.flush();
    }
}
